﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Transactions;
using System.Windows.Forms;
using Common.Tools;
using ResourceCollectionDomain.Entity;

namespace ResourceCollectionSys.Service
{
    public class VideoTranslationService
    {
        private static SqlHelper _sqlHelper = new SqlHelper("Data Source=203.195.177.228;Initial Catalog=Discuz;User ID=sa;Password=HM57g9A3k4XCL;Integrated Security=False");
        public static string ErrorMessage { get; set; }
        public static int SuccessCount { get; set; }
        public static bool IsWorcking { get; set; }
        /// <summary>
        /// 视图转存数据
        /// </summary>
        public static void TanslationVideoDataToBBs()
        {
            IsWorcking = true;
            ErrorMessage = string.Empty;
            while (IsWorcking)
            {
                try
                {
                    #region 开始执行
                    using (var db = new DBDataContext())
                    {
                        var videos = db.Video.Where(x => x.HasTranslated == false).Take(20).ToList();
                        if (videos.Count == 0)
                            Thread.Sleep(10000);//没有数据则休息10秒
                        foreach (Video video in videos)
                        {
                            try
                            {
                                string title = "《" + video.Name + "》高清迅雷BT种子下载";
                                string content = video.Description + "<br/><img src='" + video.DefaultImgUrl + "'></img>" +
                                                 "<br/>下载地址：<a href='" + video.Url + "' onclick='customDownLoad()' target='_blank'>点击下载(深圳电信)</a>";
                                #region 插入主题表
                                var maxpid = _sqlHelper.ExecuteScalar("select max(pid) from dnt_posts1");
                                if (maxpid == null || string.IsNullOrWhiteSpace(maxpid.ToString()))
                                    maxpid = 0;
                                int pid = Convert.ToInt32(maxpid) + 1;
                                SqlParameter[] para0 = new SqlParameter[]
                        {
                            new SqlParameter("@fid", 5),//板块
                            new SqlParameter("@iconid",Convert.ToInt16(0)),//主题图标
                            new SqlParameter("@typeid", Convert.ToInt32(0)),//主题分类
                            new SqlParameter("@readperm",Convert.ToInt32(0)),//阅读权限
                            new SqlParameter("@price", Convert.ToInt16(0)),//主题售价
                            new SqlParameter("@poster", "admin"),//作者
                            new SqlParameter("@posterid", Convert.ToInt32(1)),//作者ID
                            new SqlParameter("@title", title),//标题
                            new SqlParameter("@attention", Convert.ToInt32(0)),
                            new SqlParameter("@postdatetime", DateTime.Now.ToString()),//发布时间
                            new SqlParameter("@lastpost", DateTime.Now.ToString()),//最后回复帖子时间
                            new SqlParameter("@lastpostid", pid),//最后回复帖子ID
                            new SqlParameter("@lastposter", "admin"),//最后回复用户名
                            new SqlParameter("@lastposterid", Convert.ToInt32(1)),//最后回复用户名ID
                             new SqlParameter("@views", Convert.ToInt32(4)),//查看数
                            new SqlParameter("@replies", Convert.ToInt32(0)),//回复数
                            new SqlParameter("@displayorder", Convert.ToInt32(0)),//>0为置顶,<0不显示,==0正常   -1为回收站   -2待审核
                            new SqlParameter("@highlight", ""),//主题高亮识别号
                            new SqlParameter("@digest", Convert.ToInt16(0)),//精华级别,1~3
                            new SqlParameter("@rate", Convert.ToInt32(0)),//评分分数
                            new SqlParameter("@hide", Convert.ToInt32(0)),//是否为回复可见帖
                            new SqlParameter("@attachment", Convert.ToInt32(0)),//是否含有附件
                            new SqlParameter("@moderated", Convert.ToInt16(0)),//是否被执行管理操作
                            new SqlParameter("@closed", Convert.ToInt32(0)),//是否关闭,如果数值>1,值代表转向目标主题的tid
                            new SqlParameter("@magic", Convert.ToInt32(0)),//魔法id
                            new SqlParameter("@identify", Convert.ToInt32(0)),//被鉴定的id
                            new SqlParameter("@special", Convert.ToInt16(0)),

                        };
                                string add0 = "insert into dnt_topics(fid,iconid,typeid,readperm,price,poster,posterid," +
                                    "title,attention,postdatetime,lastpost,lastpostid,lastposter,lastposterid,views," +
                                    "replies,displayorder,highlight,digest,rate,hide,attachment,moderated,closed,magic," +
                                    "identify,special) values(@fid,@iconid,@typeid,@readperm,@price,@poster,@posterid," +
                                    "@title,@attention,@postdatetime,@lastpost,@lastpostid,@lastposter,@lastposterid,@views," +
                                    "@replies,@displayorder,@highlight,@digest,@rate,@hide,@attachment,@moderated,@closed,@magic," +
                                    "@identify,@special);SELECT @@IDENTITY";
                                #endregion
                                using (var scope = new TransactionScope())
                                {
                                    try
                                    {
                                        var id = _sqlHelper.ExecuteScalar(add0, para0);
                                        #region 插入帖子表

                                        int tid = Convert.ToInt32(id);

                                        SqlParameter[] para1 = new SqlParameter[]
                            {
                                new SqlParameter("@pid", pid),
                                new SqlParameter("@fid", Convert.ToInt32(5)),
                                new SqlParameter("@tid", tid),
                                new SqlParameter("@parentid", pid), //父帖ID
                                new SqlParameter("@layer", Convert.ToInt32(0)), //帖子所处层次
                                new SqlParameter("@poster", "admin"), //
                                new SqlParameter("@posterid", Convert.ToInt32(1)),
                                new SqlParameter("@title", title),
                                new SqlParameter("@postdatetime", DateTime.Now.ToString()),
                                new SqlParameter("@message", content), //内容
                                new SqlParameter("@ip", "113.91.77.252"),
                                new SqlParameter("@lastedit", ""),
                                new SqlParameter("@invisible", Convert.ToInt32(0)),
                                new SqlParameter("@usesig", Convert.ToInt32(0)), //是否启用签名
                                new SqlParameter("@htmlon", Convert.ToInt32(0)), //是否支持html
                                new SqlParameter("@smileyoff", Convert.ToInt32(0)), //是否关闭smaile表情
                                new SqlParameter("@parseurloff", Convert.ToInt32(0)), //是否关闭url自动解析
                                new SqlParameter("@bbcodeoff", Convert.ToInt32(0)), //是否支持UBB
                                new SqlParameter("@attachment", Convert.ToInt32(0)), //是否含有附件
                                new SqlParameter("@rate", Convert.ToInt32(0)), //评分分数
                                new SqlParameter("@ratetimes", Convert.ToInt32(0)), //评分次数


                            };
                                        string add1 =
                                            "insert into dnt_posts1 values(@pid,@fid,@tid,@parentid,@layer,@poster,@posterid,@title,@postdatetime," +
                                            "@message,@ip,@lastedit,@invisible,@usesig,@htmlon,@smileyoff,@parseurloff,@bbcodeoff,@attachment,@rate," +
                                            "@ratetimes)";

                                        #endregion
                                        _sqlHelper.ExecuteNonQuery(add1, para1);

                                        scope.Complete();
                                    }
                                    catch (Exception ex)
                                    {
                                        ErrorMessage += ex.ToString();
                                        IsWorcking = false;
                                        scope.Dispose();
                                        throw;
                                    }
                                }
                                video.HasTranslated = true;
                                db.SubmitChanges();
                                SuccessCount++;
                                Application.DoEvents();
                            }
                            catch (Exception ex)
                            {
                                if (ex.ToString().Contains("插入重复键的行"))
                                {
                                    video.HasTranslated = true;
                                    db.SubmitChanges();
                                    continue;
                                }
                                else
                                {
                                    throw;
                                }

                            }
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    ErrorMessage += ex.ToString();
                    IsWorcking = false;
                }

            }
        }
        /// <summary>
        /// 修改视频内容
        /// </summary>
        public static void EditContent()
        {
            IsWorcking = true;
            ErrorMessage = string.Empty;
            while (IsWorcking)
            {
                try
                {
                    #region 开始执行

                    using (var db = new DBDataContext())
                    {
                        var videos = db.Video.Where(x => x.HasTranslated == false).Take(20).ToList();
                        if (videos.Count == 0)
                            Thread.Sleep(10000); //没有数据则休息10秒
                        foreach (Video video in videos)
                        {
                            string title = "《" + video.Name + "》高清迅雷BT种子下载";
                            string content = video.Description + "<br/><img src='" + video.DefaultImgUrl + "'></img>" +
                                             "<br/>下载地址：<a href='" + video.Url +
                                             "' onclick='customDownLoad()' target='_blank'>点击下载(深圳电信)</a>" +
                                             "<br/><span style='color:red'>如果点击没有打开正确的下载页面，请使用备用下载地址：<span>" +
                                             "<a href='" + video.Url + "' target='_blank'>下载</a>";
                            string sql0 = "select pid from dnt_posts1 where title=@title";
                            SqlParameter[] para0 = new SqlParameter[]
                            {
                                new SqlParameter("@title", title),
                            };
                            var opid = _sqlHelper.ExecuteScalar(sql0, para0);
                            if (!string.IsNullOrWhiteSpace(opid.ToString()))
                            {
                                string sql1 = "update dnt_posts1 SET [message]=@message where pid=@pid";
                                SqlParameter[] para1 = new SqlParameter[]
                                {
                                    new SqlParameter("@pid", Convert.ToInt32(opid)),
                                    new SqlParameter("@message", content), //内容
                                };
                                _sqlHelper.ExecuteNonQuery(sql1, para1);
                            }
                            video.HasTranslated = true;
                            db.SubmitChanges();
                            SuccessCount++;
                        }

                    }


                    #endregion
                }
                catch (Exception ex)
                {
                    ErrorMessage += ex.ToString();
                    IsWorcking = false;
                }

            }
        }
    }
}
